// DriveNotes. Copyright (c) 2011, Andrei Senchuk. All rights reserved.
package net.taviscaron.drivenotes.server.service;

import java.util.List;
import net.taviscaron.drivenotes.server.model.dao.PlaceDAO;
import net.taviscaron.drivenotes.server.model.validators.Validator;
import net.taviscaron.drivenotes.server.util.EntityUtils;
import net.taviscaron.drivenotes.shared.exceptions.InvalidEntityException;
import net.taviscaron.drivenotes.shared.model.entity.Place;
import net.taviscaron.drivenotes.shared.model.entity.User;
import net.taviscaron.drivenotes.shared.service.PlaceService;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.transaction.annotation.Transactional;

/**
 * Place servi
 * @author Andrei Senchuk
 */
public class PlaceServiceImpl implements PlaceService {
    private Validator<Place> placeValidator;
    private PlaceDAO placeDAO;

    @Required
    public void setPlaceDAO(PlaceDAO placeDAO) {
        this.placeDAO = placeDAO;
    }

    @Required
    public void setPlaceValidator(Validator<Place> placeValidator) {
        this.placeValidator = placeValidator;
    }

    @Transactional
    public List<Place> findPlacesByUser(User user) {
        List<Place> places = placeDAO.findByOwnerId(user.getId());
        for(int i = 0; i < places.size(); i++) {
            places.set(i, EntityUtils.createPlaceValueObject(places.get(i)));
        }
        return places;
    }

    @Transactional
    public Place findPlace(Long id, User author) {
        Place place = placeDAO.findByOwnerAndId(author, id);
        return EntityUtils.createPlaceValueObject(place);
    }

    @Transactional
    public void savePlace(Place place) throws InvalidEntityException {
        placeValidator.validate(place);
        placeDAO.save(place);
    }

    @Transactional
    public void removePlaceById(Long id) {
        Place place = placeDAO.findById(id);
        placeDAO.remove(place);
    }
}
